package fr.rinie.android_first_step;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import java.io.IOException;
import java.util.List;


public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List<FishContainer.Fish> listOfAllFish = extractFishFromDatabase();
        ListView listView = (ListView) findViewById(R.id.listfish);
        if (null != listOfAllFish && listOfAllFish.size() != 0) {
            FishAdapter fishAdapter = new FishAdapter(MyActivity.this, R.layout.listfish, listOfAllFish);
            listView.setAdapter(fishAdapter);
            EditText inputSearch = (EditText) findViewById(R.id.inputSearch);
            inputSearch.addTextChangedListener(new MyTextWatcher(fishAdapter));
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                @SuppressWarnings("unchecked")
                public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                    Bundle bundle = new Bundle();
                    FishContainer.Fish fish = ((FishAdapter) a.getAdapter()).getItem(position);
                    bundle.putSerializable("value", fish);
                    Intent intent = new Intent(MyActivity.this, DisplayFishDetails.class);
                    intent.putExtras(bundle);
                    MyActivity.this.startActivity(intent);
                }
            });
        }
    }

    private List<FishContainer.Fish> extractFishFromDatabase() {
        FishDB fishDB = new FishDB(this);
        try {
            fishDB.createDataBase();
        } catch (IOException e) {
            throw new Error("unable to create database");
        }
        fishDB.open();
        List<FishContainer.Fish> listOfFish = fishDB.getAllFish();
        fishDB.close();
        return listOfFish;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.about:
                AlertDialog.Builder adb = new AlertDialog.Builder(MyActivity.this);
                adb.setTitle("A propos:");
                adb.setMessage(getString(R.string.aboutInfo));
                adb.setPositiveButton("Ok", null);
                adb.show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.aboutmenu, menu);
        return true;
    }
}
